package com.xgy.vue_role_system.config.security.handler;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xgy.vue_role_system.config.redis.RedisService;
import com.xgy.vue_role_system.entity.User;
import com.xgy.vue_role_system.utils.JwtUtils;
import com.xgy.vue_role_system.utils.LoginResult;
import com.xgy.vue_role_system.utils.ResultCode;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 登录认证成功处理器类
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private RedisService redisService;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //设置响应的编码格式
        response.setContentType("application/json;charset=utf-8");
        //获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //获取当前登录用户的信息，因为user已经定义成userDetails类型了，所以直接用user接收即可
        User user = (User) authentication.getPrincipal();

        //生成token
        String token = jwtUtils.generateToken(user);
        //设置token的签名密钥及过期的时间
        long expireTime = Jwts.parser()
                .setSigningKey(jwtUtils.getSecret())        //设置签名密钥
                .parseClaimsJws(token.replace("jwt_", "")) //把生成的token中的"jwt_"去掉
                .getBody().getExpiration().getTime();       //设置过期时间

        //创建LoginResult登录结果对象，携带 用户 id 及 token信息给前端
        LoginResult loginResult = new LoginResult(user.getId(), ResultCode.SUCCESS,token,expireTime);

        //将结果对象转换成json格式，并消除循环引用
        String result = JSON.toJSONString(loginResult, SerializerFeature.DisableCircularReferenceDetect);

        //将结果保存到输出流中写出
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();

        //将token信息保存到Redis中
        String tokenKey = "token_" + token;
        redisService.set(tokenKey,token,jwtUtils.getExpiration()/1000);
    }
}
